//
//  searchViewController.m
//  Alltelevisionnews
//
//  Created by dllo on 15/12/1.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
//

#import "searchViewController.h"

@interface searchViewController ()<UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, strong)UITableView *myTabelView;
@property(nonatomic, strong)MBProgressHUD *hud;
@property(nonatomic, strong)NSMutableArray *arr;
@property(nonatomic, strong)NSMutableArray *titleArr;
@property(nonatomic, strong)NSString *tempid;

@end

@implementation searchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.myTabelView = [[UITableView alloc] init];
    [self.view addSubview:self.myTabelView];
    [self.myTabelView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.view);
        make.height.equalTo(self.view);
    }];
    self.myTabelView.rowHeight = 120;
    self.myTabelView.dataSource = self;
    self.myTabelView.delegate = self;
    
    [self createData];
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.labelText = @"正在加载";
    
    if ([ZDQSingleton shareSingleton].isLongin == YES) {
        
        self.myTabelView.backgroundColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.3 alpha:1];
        
    } else {
        
        self.myTabelView.backgroundColor = [UIColor whiteColor];
    }
    
}

- (void)createData {
    // 判断是否有空格
    if ([self.strNews hasPrefix:@" "] || [self.strNews hasSuffix:@" "] || [self.strNews containsString:@" "]) {
        UIAlertController *aleryController = [UIAlertController alertControllerWithTitle:@"对不起" message:@"搜索的新闻不存在" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:aleryController animated:YES completion:nil];
        UIAlertAction *leftAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            [self.navigationController popViewControllerAnimated:YES];        }];
        
        [aleryController addAction:leftAction];
    }
    /////如果没有空格
    else {
        ////// 转码
        NSString *urlString = self.strNews;
        urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:urlString]];
        NSLog(@"%@", urlString);
        [SLAFNetWorkTool cacheGetWithURL:[NSString stringWithFormat:@"http://api.3g.ifeng.com/clientAggregateSearch?k=%@&gv=4.6.5&av=0&proid=ifengnews&os=ios_8.4.1&vt=5&screen=640x960&publishid=4002&uid=00843d54db6759a6011ed5becdd59b2e5420d3fd", urlString] cookie:nil success:^(id responseObject) {
            //        NSLog(@"%@", responseObject);
            self.arr = [NSMutableArray array];
            self.titleArr = [NSMutableArray array];
            // 判断数组是否为空
            NSNull *null = [NSNull null];
            if (responseObject[@"data"][@"item"] == null && responseObject[@"picData"][@"item"] == null && responseObject[@"videoData"][@"item"] == null) {
                UIAlertController *aleryController = [UIAlertController alertControllerWithTitle:@"对不起" message:@"搜索的新闻不存在" preferredStyle:UIAlertControllerStyleAlert];
                [self presentViewController:aleryController animated:YES completion:nil];
                UIAlertAction *leftAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [self.navigationController popViewControllerAnimated:YES];
                }];
                
                [aleryController addAction:leftAction];
            }
            else {
                if (responseObject[@"data"][@"item"] != null) {
                    NSArray *tempArr = responseObject[@"data"][@"item"];
                    [self.arr addObject:[SearchMdel baseModelByArr:tempArr]];
                    [self.titleArr addObject:@"文章"];
                }
                if (responseObject[@"picData"][@"item"] != null) {
                    NSArray *tempArr = responseObject[@"picData"][@"item"];
                    [self.arr addObject:[SearchMdel baseModelByArr:tempArr]];
                    [self.titleArr addObject:@"图集"];
                }
                if (responseObject[@"videoData"][@"item"] != null) {
                    NSArray *tempArr = responseObject[@"videoData"][@"item"];
                    [self.arr addObject:[SearchMdel baseModelByArr:tempArr]];
                    [self.titleArr addObject:@"视频"];
                    
                }
            }
            [self.myTabelView reloadData];
            self.hud.hidden = YES;
        } failure:^(NSError *error) {
            
        }];
    }
}
// 分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
   
        return self.titleArr.count;
    
}
// 分区标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection: (NSInteger)section {
    return self.titleArr[section];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.arr[section] count];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *arr = self.arr[indexPath.section];
    SearchMdel *search = arr[indexPath.row];
    if (![search.thumbnail isEqualToString:@""]) {
        static NSString *reuse = @"reuse";
        TopicPageCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[TopicPageCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuse];
        }
        if ([ZDQSingleton shareSingleton].isLongin == YES) {
            cell.titleLabel.textColor = [UIColor whiteColor];
            cell.picImage.alpha = 0.4;
            
        } else {
            
            cell.titleLabel.textColor = [UIColor blackColor];
            cell.picImage.alpha = 1;
        }

        // 字高亮
        NSMutableAttributedString *titleStr = [[NSMutableAttributedString alloc] initWithString:search.title];
        NSInteger length = (NSInteger)self.strNews.length;
        for (NSInteger i = 0; i < length; i++) {
            NSString *str = [self.strNews substringWithRange:NSMakeRange(i, 1)];
            NSRange range = [search.title rangeOfString:str];
            [titleStr setAttributes:@{NSForegroundColorAttributeName:[UIColor redColor], NSFontAttributeName: [UIFont systemFontOfSize:20]} range:range];
        }
        
        [cell.picImage sd_setImageWithURL:[NSURL URLWithString:search.thumbnail] placeholderImage:[UIImage imageNamed:@"pac.png"]];
        cell.titleLabel.attributedText = titleStr;
        
        cell.backgroundColor = [UIColor clearColor];
        
        
        return cell;
    }
    else {
        static NSString *reuse = @"reaae";
        DetaisViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[DetaisViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuse];
        }
        
        if ([ZDQSingleton shareSingleton].isLongin == YES) {
            cell.titleLabel.textColor = [UIColor whiteColor];
        } else {
            
            cell.titleLabel.textColor = [UIColor blackColor];
            
        }

        // 字高亮
        NSMutableAttributedString *titleStr = [[NSMutableAttributedString alloc] initWithString:search.title];
        NSInteger length = (NSInteger)self.strNews.length;
        for (NSInteger i = 0; i < length; i++) {
            NSString *str = [self.strNews substringWithRange:NSMakeRange(i, 1)];
            NSRange range = [search.title rangeOfString:str];
            [titleStr setAttributes:@{NSForegroundColorAttributeName:[UIColor redColor], NSFontAttributeName: [UIFont systemFontOfSize:20]} range:range];
        }
        
        cell.titleLabel.numberOfLines = 0;
        cell.titleLabel.attributedText = titleStr;
        cell.backgroundColor = [UIColor clearColor];
        
        return cell;
    }
}
#pragma mark 又解析一遍
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *tempArr = self.arr[indexPath.section];
    SearchMdel *search = tempArr[indexPath.row];
    self.tempid = search.links[0][@"url"];
    [self catMama];
}

- (void)catMama {
    [SLAFNetWorkTool cacheGetWithURL:[NSString stringWithFormat:@"%@&gv=4.6.5&av=0&proid=ifengnews&os=ios_8.4.1&vt=5&screen=640x960&publishid=4002&uid=00843d54db6759a6011ed5becdd59b2e5420d3fd", self.tempid] cookie:nil success:^(id responseObject) {
        DetaisWebViewController *webVC = [[DetaisWebViewController alloc] init];
        webVC.strId = responseObject[@"body"][@"shareurl"];       NSLog(@"%@", webVC.strId);
        [self.navigationController pushViewController:webVC animated:YES];
    } failure:^(NSError *error) {
        
    }];
}







- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
